<template>
    <div class="breadcrumbs">
        <a-breadcrumb :routes="breadcrumbsItems" separator="|">
            <template slot="itemRender" slot-scope="{ route }">
                <router-link :to="route.to">
                    {{ route.text }}
                </router-link>
            </template>
        </a-breadcrumb>
    </div>
</template>
<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import { RouteRecord } from 'vue-router';
import { Grade } from '@/enums/index';

interface BreadcrumbsItem {
    breadcrumbName: string;
    disabled: boolean;
    exact: boolean;
    text: string | number;
    to: string | object;
}
@Component
export default class Breadcrumbs extends Vue {
    private routes: RouteRecord[] = [];

    private breadcrumbsItems: BreadcrumbsItem[] = [];

    private mounted() {
        this.changeHistory();
        console.log(this.breadcrumbsItems);
    }

    @Watch('$route.matched')
    private changeHistory() {
        this.routes = this.$route.matched; // 路由历史记录
        this.routes.forEach(route => {
            if (route.meta.grade !== Grade.Father) {
                const item: BreadcrumbsItem = {
                    disabled: false,
                    exact: true,
                    text: '',
                    to: '',
                    breadcrumbName: '',
                };
                item.text = route.meta.title;
                item.breadcrumbName = route.meta.title;
                item.to = route.path;
                this.breadcrumbsItems.push(item);
            }
        });

        this.breadcrumbsItems = this.unique(this.breadcrumbsItems);
    }
    // 对象去重
    private unique(childs: BreadcrumbsItem[]) {
        const res = new Map();
        return childs.filter(a => !res.has(a.text) && res.set(a.text, 1));
    }
}
</script>
<style scoped>
.breadcrumbs {
    width: 50vw;
}

</style>